import * as cluster from "cluster";

import log from "./lib/log";
import { args } from "./lib/args";
import serviceSet from "./serviceSet";
import run from "./app";
import { Config } from "./typing";
import { EventEmitter } from "events";

if (cluster.isMaster) {
    console.log(`主进程 ${ process.pid } 正在运行....`);
    run();
} else {
    // 载入配置文件
    const config: Config = require(args["-c"]);
    const work = new EventEmitter();
    // 服务对象
    let service;

    work.on("updateConfig", (message) => {
        Object.assign(config, message.config);
    });

    work.on("getMemory", () => {
        process.send({
            type: "memory",
            serviceName: service.serviceName,
            memoryUsage: process.memoryUsage(),
        });
    });

    // 接受主进程通知
    process.on("message", (message) => {
        if (serviceSet[message.type]) {
            try {
                // 服务启动
                service = new serviceSet[message.type](config, message.type);
                service.start();
            } catch (error) {
                log.service.info(message.type, error);
                process.exit();
            }
        } else {
            work.emit(message.type, message);
        }
    });
}